package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FOLLOW_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;

    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        // 获取用户id
        Long userId = UserHolder.getUser().getId();
        // 判断是关注还是取消关注
        if (isFollow) {
            // 关注，保存到数据库
            Follow follow = new Follow();
            follow.setFollowUserId(followUserId);
            follow.setUserId(userId);
            boolean isSuccess = this.save(follow);
            if (isSuccess) {
                // 保存到数据库成功，写入Redis
                stringRedisTemplate.opsForSet().add(FOLLOW_KEY + userId, followUserId.toString());
            }
        } else {
            // 取消关注，从数据库删除
            boolean isSuccess = this.remove(
                lambdaQuery().eq(Follow::getUserId, userId).eq(Follow::getFollowUserId, followUserId).getWrapper());
            if (isSuccess) {
                // 从Redis中删除
                stringRedisTemplate.opsForSet().remove(FOLLOW_KEY + userId, followUserId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long followUserId) {
        // 获取用户id
        Long userId = UserHolder.getUser().getId();
        Integer count =
            this.lambdaQuery().eq(Follow::getUserId, userId).eq(Follow::getFollowUserId, followUserId).count();
        return Result.ok(count > 0);
    }

    @Override
    public Result bothFollow(Long id) {
        Long userId = UserHolder.getUser().getId();
        // 当前用户的set集合与目标用户的set集合取交集，交集部分就是共同关注
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(FOLLOW_KEY + userId, FOLLOW_KEY + id);
        // 如果交集为空，则说明没有共同关注
        if (intersect == null || intersect.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        // 将set集合转为long
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        // 根据id查找到对应的用户，并转为dto
        List<UserDTO> users = userService.listByIds(ids).stream()
            .map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        return Result.ok(users);
    }
}
